package com.lzb.yabbs.app;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.gitonway.lee.niftynotification.lib.Effects;
import com.gitonway.lee.niftynotification.lib.NiftyNotificationView;
import com.lzb.yabbs.AppConfig;
import com.lzb.yabbs.R;
import com.lzb.yabbs.dao.Board;
import com.lzb.yabbs.interfaces.GetBoardCallback;
import com.lzb.yabbs.interfaces.SendCardCallback;
import com.lzb.yabbs.net.GetBoardFromNet;
import com.lzb.yabbs.net.SendCardToNet;

import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

public class SendCardActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private final String TAG = getClass().getSimpleName();

    private EditText mCardTitleEt;
    private EditText mCardContentEt;
    private Spinner mSpinner;
    private TextInputLayout mTileTil;
    private TextInputLayout mContentTil;

    private int mChooseBoardId;
    private String mChooseBoardName;

    private ArrayAdapter<String> mStringArrayAdapter;

    private final int GET_BOARD_SUCESS = 0x1231;
    private final int GET_BOARD_FAIL = 0x1243;
    private final int SEND_CARD_SUCESS = 0x1324;
    private final int SEND_CARD_FAIL = 0x1001;

    private SharedPreferences sharedPreferences;

    private List<Board> mBoards = new ArrayList<>();

    private ProgressDialog mProgressDialog=null;

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_BOARD_FAIL:
                    NiftyNotificationView.build(SendCardActivity.this, "请先登录", Effects.flip, R.id.mylayout)
                            .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                            show();

                    break;
                case GET_BOARD_SUCESS:
                    String[] items = new String[mBoards.size()];
                    for (int i = 0; i < mBoards.size(); i++) {
                        items[i] = mBoards.get(i).getName();
                    }
                    mStringArrayAdapter = new ArrayAdapter<>(SendCardActivity.this, android.R.layout.simple_spinner_item, items);
                    mSpinner.setAdapter(mStringArrayAdapter);

                    break;
                case SEND_CARD_SUCESS:
                    mProgressDialog.dismiss();
                    NiftyNotificationView.build(SendCardActivity.this, "发帖成功", Effects.flip, R.id.mylayout)
                            .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                            show();
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            setResult(AppConfig.SEND_CARD_SUCESS_BACK_CODE);
                            SendCardActivity.this.finish();
                        }
                    },1000);
                    break;
                case SEND_CARD_FAIL:
                    NiftyNotificationView.build(SendCardActivity.this, "发帖失败", Effects.flip, R.id.mylayout)
                            .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                            show();
                    mProgressDialog.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_card);

        getDataFromIntent();

        mProgressDialog=new ProgressDialog(this);
        initView();
        setTitle("发帖");

        sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
    }

    private void getDataFromIntent() {
        Intent intent = getIntent();
        if (intent.getIntExtra("boardId", -1) != -1) {      //从模块列表进入
            mChooseBoardId = intent.getIntExtra("boardId", 1);
            mChooseBoardName = intent.getStringExtra("boardName");
        } else {
            mChooseBoardId = 1;
            mChooseBoardName = "社区事务";
        }
    }


    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
    }

    private void initView() {
        //mCardContentEt = (EditText) findViewById(R.id.card_content_et);
        //mCardTitleEt = (EditText) findViewById(R.id.card_title_et);
        mContentTil= (TextInputLayout) findViewById(R.id.card_content_et);
        mTileTil= (TextInputLayout) findViewById(R.id.card_title_Til);
        mCardContentEt=mContentTil.getEditText();
        mCardTitleEt=mTileTil.getEditText();
        mContentTil.setHint("内容");
        mTileTil.setHint("标题");
        mSpinner = (Spinner) findViewById(R.id.spinner);


        mStringArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{mChooseBoardName});
        mSpinner.setAdapter(mStringArrayAdapter);
        mSpinner.setOnItemSelectedListener(this);

        GetBoardFromNet.getBoards(AppConfig.URL_GET_BOARDS, new GetBoardCallback() {
            @Override
            public void success(List<Board> mBoards) {
                SendCardActivity.this.mBoards = mBoards;
                mHandler.sendEmptyMessage(GET_BOARD_SUCESS);
            }

            @Override
            public void fail(int reason) {
                mHandler.sendEmptyMessage(GET_BOARD_FAIL);
            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_sedn_card_menu:

                if (!sharedPreferences.getBoolean("login", false)) {
                    NiftyNotificationView.build(this, "请先登录", Effects.flip, R.id.mylayout)
                            .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                            show();
                    return true;
                }
                if (mCardContentEt.getText().toString().equals("") || mCardTitleEt.getText().toString().equals("") || mCardContentEt.getText().toString().equals("null") || mCardTitleEt.getText().toString().equals("null")) {
                    NiftyNotificationView.build(this, "请填写完整内容", Effects.flip, R.id.mylayout)
                            .setIcon(R.mipmap.ic_launcher).    //You must call this method if you use ThumbSlider effect
                            show();
                    return true;
                }

                mProgressDialog.setTitle("sending");
                mProgressDialog.show();
                SendCardToNet.sendCard(AppConfig.URL_SEND_CARD, getPairs(), new SendCardCallback() {
                    @Override
                    public void sucess() {
                        mHandler.sendEmptyMessage(SEND_CARD_SUCESS);
                    }

                    @Override
                    public void fail(int reason) {
                        mHandler.sendEmptyMessage(SEND_CARD_FAIL);
                    }
                });
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private List<BasicNameValuePair> getPairs() {
        List<BasicNameValuePair> pairs = new ArrayList<>();
        SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);

        BasicNameValuePair pair = new BasicNameValuePair("uid", sharedPreferences.getInt("uid", 0) + "");
        BasicNameValuePair pair1 = new BasicNameValuePair("board", mChooseBoardId + "");
        BasicNameValuePair pair2 = new BasicNameValuePair("content", mCardContentEt.getText().toString());
        BasicNameValuePair pair3 = new BasicNameValuePair("title", mCardTitleEt.getText().toString());
        BasicNameValuePair pair4 = new BasicNameValuePair("token", sharedPreferences.getString("token", ""));

        pairs.add(pair);
        pairs.add(pair1);
        pairs.add(pair2);
        pairs.add(pair3);
        pairs.add(pair4);
        return pairs;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.send_card_list_menu, menu);
        return true;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG, "onItemSelected position" + position);
        if(position<mBoards.size()) {
            mChooseBoardName = mBoards.get(position).getName();
            mChooseBoardId = mBoards.get(position).getId();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        Log.d(TAG, "onNothingSelected");

    }
}
